<template>
    <div class="saveUpdate">
        <el-dialog :close-on-click-modal="false" :title="id?'修改代理':'新增代理'" :visible.sync="showDialog" @close="$emit('update:showUpdate', false)"
                   :showUpdate="showUpdate" width="500px">
            <el-form :model="DetailInfo" ref="saveChn" label-width="130px" size="mini">
                <dialog-wrapper :MaxWidth="400">
                    <el-form-item label="代理头像：" prop="avatar" :rules="[{ required: true, message: '头像不能为空' }]" v-if="DetailInfo.avatar">
                        <croppa @file-choose="handlePictureCardPreview" class="avatar-uploader avatar" :file-size-limit='50000'
                                 placeholder="选择图片" :placeholder-font-size="16" v-loading="fullscreenLoading"   :initial-image="'http://image.barchain.net/'+DetailInfo.avatar"></croppa>
                    </el-form-item>
                    <el-form-item label="代理账号：" prop="user_name" :rules="[{ required: true, message: '代理名称不能为空'}]">
                        <el-input v-model="DetailInfo.user_name" :disabled="!!id" placeholder="请输入代理名称..."></el-input>
                    </el-form-item>
                    <el-form-item label="昵称：" v-if="id?true:false">
                        <el-input v-model="DetailInfo.nickname"></el-input>
                    </el-form-item>
                    <el-form-item prop="mch_ids" label="商户：" :rules="[{ required: true, message: '请选择商户', trigger: 'blur' }]">
                        <el-select v-model="DetailInfo.mch_ids" clearable multiple placeholder="请选择">
                            <el-option v-for="item in MerchantsList" :key="item.id" :label="item.name"
                                       :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="IP白名单：">
                        <el-input v-model="white_ips" type="textarea"></el-input>
                    </el-form-item>
                    <el-form-item label="预警金额：" prop="warning_amount"
                                  :rules="[ { type: 'number', message: '报警金额必须为数字值'}]">
                        <el-input v-model.number="DetailInfo.warning_amount"></el-input>
                    </el-form-item>
                    <el-form-item label="是否使用安全码：">
                        <el-switch v-model="DetailInfo.use_vcode"></el-switch>
                    </el-form-item>
                    <el-form-item label="代理状态：">
                        <el-switch v-model="DetailInfo.enable"></el-switch>
                    </el-form-item>
                    <el-form-item label="备注：">
                        <el-input v-model="DetailInfo.remark"></el-input>
                    </el-form-item>
                </dialog-wrapper>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="$emit('update:showUpdate', false)" size="small">取 消</el-button>
                <el-button v-if="id" type="primary" :loading="loading" @click="updateDetail" size="small"  :disabled="fullscreenLoading">确 定
                </el-button>
                <el-button v-else type="primary" :loading="loading" @click="saveDetail" size="small"  :disabled="fullscreenLoading">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import DialogWrapper from '@/components/DialogWrapper'
    import {getAgencyDetail, saveAgency, updateAgency,getQiniuUploadToken,qiniuUpload} from '@/api'
    import {useVcode} from "../../utils/CommonJs";
    import {uuid} from '@/utils/uuid'

    export default {
        components: {DialogWrapper},
        data() {
            return {
                setbank: false,
                showDialog: this.showUpdate,
                loading: false,
                fullscreenLoading: false,
                white_ips: '',
                newavatar: null,
                myCroppa: {},
                DetailInfo: {
                    mch_ids: null,
                    enable: true,
                    warning_amount: 1000000,
                    use_vcode: false,
                },
            }
        },
        props: {
            showUpdate: {
                type: Boolean,
                default: false
            },
            id: {
                type: Number
            },
            AgencyType: {
                type: Object
            },
            settleCycle: {
                type: Object
            },
            MerchantsList: {
                type: Array
            },
        },
        created() {
            if (this.id) {
                this.getDetail()
            }
        },
        methods: {
            handlePictureCardPreview(f) {
                if ( f.size > 50000) {
                    this.$message({type: 'error', message: '文件大小不能超过50kb'})
                    return
                }
                this.fullscreenLoading = true;
                getQiniuUploadToken().then(res => {
                    if (res.status === 0) {
                        //创建新文件对象（实现更名）
                        var newfile = new File([f],uuid()+f.name.substring(f.name.lastIndexOf('.')),{type:"image/jpeg"});
                        let data = new FormData()
                        data.append('file', newfile)
                        data.append('key', newfile.name)
                        data.append('token', res.data.token)
                        qiniuUpload(data).then(res => {
                            // this.DetailInfo.avatar = res.key
                            this.$set(this.DetailInfo,'avatar', res.key)
                            this.$message({ message: '上传成功。',type: 'success' })
                            this.fullscreenLoading = false;
                        })
                    }
                })
            },
            saveDetail() {
                useVcode(this, () => {
                    this.$refs.saveChn.validate(valid => {
                        if (valid) {
                            let list = [];
                            if (this.white_ips.trim() != "") {
                                list = this.white_ips.split(',')
                            }
                            this.DetailInfo.white_ips = list;
                            saveAgency(Object.assign({}, this.DetailInfo, {warning_amount: Number(this.DetailInfo.warning_amount) * 100})).then(res => {
                                if (res.status === 0) {
                                    this.$message({message: `新增成功, 代理密码为 ${res.data.password}`, type: 'success'})
                                    this.$emit('update:showUpdate', false)
                                }
                            })
                        }
                    })
                })

            },
            updateDetail() {
                useVcode(this, () => {
                    this.$refs.saveChn.validate(valid => {
                        if (valid) {
                            let list = [];
                            if (this.white_ips.trim() != "") {
                                list = this.white_ips.split(',')
                            }
                            this.DetailInfo.white_ips = list;
                            updateAgency(Object.assign({}, this.DetailInfo, {warning_amount: Number(this.DetailInfo.warning_amount) * 100}), this.id).then(res => {
                                if (res.status === 0) {
                                    this.$message({message: '编辑成功。', type: 'success'})
                                    this.$emit('update:showUpdate', false)
                                }
                            })
                        }
                    })
                })
            },
            getDetail() {
                getAgencyDetail(this.id).then(res => {
                    if (res.status === 0) {
                        this.DetailInfo = res.data
                        this.DetailInfo = Object.assign(this.DetailInfo, {warning_amount: Number(this.DetailInfo.warning_amount) / 100})
                        let {user_name, use_vcode, enable, nickname, mchs, min_amount, max_amount, warning_amount, remark, white_ips,avatar} = res.data
                        let mchsId = []
                        mchs.forEach(function (item) {
                            mchsId.push(item.id)
                        })
                        if (white_ips != null) {
                            this.white_ips = white_ips.toString();
                        }
                        this.DetailInfo = {
                            user_name,
                            use_vcode,
                            enable,
                            nickname,
                            mch_ids: mchsId || [],
                            min_amount,
                            max_amount,
                            warning_amount,
                            remark,
                            avatar
                        }
                        this.newavatar='http://image.barchain.net/'+this.DetailInfo.avatar

                    }
                })
            }
        },
        watch: {
            showUpdate() {
                this.showDialog = this.showUpdate
            }
        }
    }
</script>
